package sg.edu.nus.comp.icreate.ivletalk.events;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import sg.edu.nus.comp.icreate.ivletalk.EventNoRefreshBaseActivity;
import sg.edu.nus.comp.icreate.ivletalk.R;
import sg.edu.nus.comp.icreate.ivletalk.User;
import sg.edu.nus.comp.icreate.ivletalk.module.MainActivity;
import sg.edu.nus.comp.icreate.ivletalk.utils.net.DataPoster;
import sg.edu.nus.comp.icreate.ivletalk.utils.net.DataPuller;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class NewEventActivity extends EventNoRefreshBaseActivity {

	public static List<String> category = new ArrayList<String>();
	public static List<String> committee = new ArrayList<String>();
	public static final int REQUEST_CODE_NEW_EVENT = 1002;
	private EditText editTitle, editOrganizer, editDate, editVenue, editPrice, editContact, editDescription, editTags, editAgenda;
	private Button submitButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_event);
		getCategory();
		getCommittee();
		Spinner spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
		ArrayAdapter<String> categoriesAdapter = new ArrayAdapter<String>(NewEventActivity.this, android.R.layout.simple_spinner_item, category);
		spinnerCategory.setAdapter(categoriesAdapter);
		Spinner spinnerCommittee = (Spinner) findViewById(R.id.spinnerCommittee);
		ArrayAdapter<String> committeeAdapter = new ArrayAdapter<String>(NewEventActivity.this, android.R.layout.simple_spinner_item, committee);
		spinnerCommittee.setAdapter(committeeAdapter);

		editTitle = (EditText) findViewById(R.id.editTitle);
		editOrganizer = (EditText) findViewById(R.id.editOrganizer);
		editDate = (EditText) findViewById(R.id.editDate);
		editVenue = (EditText) findViewById(R.id.editVenue);
		editPrice = (EditText) findViewById(R.id.editPrice);
		editContact = (EditText) findViewById(R.id.editContact);
		editDescription = (EditText) findViewById(R.id.editDescription);
		editTags = (EditText) findViewById(R.id.editTags);
		editAgenda = (EditText) findViewById(R.id.editAgenda);

		spinnerCommittee = (Spinner) findViewById(R.id.spinnerCommittee);
		spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
		submitButton = (Button) findViewById(R.id.submitButton);
		submitButton.setOnClickListener(new SubmitButtonOnClickListener(this, spinnerCommittee, spinnerCategory, editTitle, editOrganizer, editDate, editVenue,
				editPrice, editContact, editDescription, editTags, editAgenda));

	}

	private class SubmitButtonOnClickListener implements OnClickListener {
		private static final String KEY_APIKEY = "APIKey";
		private static final String KEY_TITLE = "Title";
		private static final String KEY_CAT = "CategoryID";
		private static final String KEY_COMM = "CommitteeID";
		private static final String KEY_TAGS = "tags";
		private static final String KEY_AGENDA = "evtAgenda";
		private static final String KEY_CONTACT = "evtContact";
		private static final String KEY_DATE = "evtdatetimestring";
		private static final String KEY_DES = "evtdesp";
		private static final String KEY_PRICE = "evtPrice";
		private static final String KEY_VENUE = "Venue";
		private static final String KEY_START = "evtStartDate";
		private static final String KEY_END = "evtEndDate";
		private static final String KEY_ORG = "evtOrganizer";

		private static final String KEY_AUTH_TOKEN = "AuthToken";

		private static final String URL_NEW_POST = "https://ivle.nus.edu.sg/api/Lapi.svc/StudentEvent_PostNewEvent_JSON";
		EditText editTitle, editOrganizer, editDate, editVenue, editPrice, editContact, editDescription, editTags, editAgenda;
		Spinner spinnerCommittee, spinnerCategory;

		public SubmitButtonOnClickListener(NewEventActivity newEventActivity, Spinner spinnerCommittee, Spinner spinnerCategory, EditText editTitle,
				EditText editOrganizer, EditText editDate, EditText editVenue, EditText editPrice, EditText editContact, EditText editDescription,
				EditText editTags, EditText editAgenda) {
			this.editContact = editContact;
			this.editDate = editDate;
			this.editDescription = editDescription;
			this.editOrganizer = editOrganizer;
			this.editPrice = editPrice;
			this.editTitle = editTitle;
			this.editVenue = editVenue;
			this.spinnerCategory = spinnerCategory;
			this.spinnerCommittee = spinnerCommittee;
			this.editTags = editTags;
			this.editAgenda = editAgenda;

		}

		@SuppressLint("SimpleDateFormat")
		@Override
		public void onClick(View v) {
			String title = (String) editTitle.getText().toString();
			Log.d("33BDebugTag", "Value: " + title);
			String venue = (String) editVenue.getText().toString();
			String org = (String) editOrganizer.getText().toString();
			String des = (String) editDescription.getText().toString();
			String price = (String) editPrice.getText().toString();
			String date = (String) editDate.getText().toString();
			String contact = (String) editContact.getText().toString();
			String tags = (String) editTags.getText().toString();
			String agenda = (String) editAgenda.getText().toString();

			Date start = new Date();
			Date end = new Date();
			Calendar cal = Calendar.getInstance();
			cal.setTime(start);

			cal.add(Calendar.DATE, 7);
			start = cal.getTime();
			cal.add(Calendar.DATE, 31);
			end = cal.getTime();

			DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
			String sDate = df.format(start);
			String eDate = df.format(end);

			String url = URL_NEW_POST;
			DataPoster httpPoster = new DataPoster(url);
			httpPoster.addNameValuePair(KEY_AUTH_TOKEN, User.getInstance().getToken());
			httpPoster.addNameValuePair(KEY_APIKEY, MainActivity.APIKEY);
			httpPoster.addNameValuePair(KEY_TITLE, title);
			httpPoster.addNameValuePair(KEY_TAGS, tags);
			httpPoster.addNameValuePair(KEY_AGENDA, agenda);
			httpPoster.addNameValuePair(KEY_CONTACT, contact);
			httpPoster.addNameValuePair(KEY_DATE, date);
			httpPoster.addNameValuePair(KEY_DES, des);
			httpPoster.addNameValuePair(KEY_PRICE, price);
			httpPoster.addNameValuePair(KEY_VENUE, venue);
			httpPoster.addNameValuePair(KEY_ORG, org);
			httpPoster.addNameValuePair(KEY_START, sDate);
			httpPoster.addNameValuePair(KEY_END, eDate);

			httpPoster.addNameValuePair(KEY_CAT, ((String) spinnerCategory.getSelectedItem()));

			httpPoster.addNameValuePair(KEY_COMM, ((String) spinnerCommittee.getSelectedItem()));

			if (validate(title, org) == false) {

				httpPoster.execute();
				try {
					httpPoster.get();
					setResult(RESULT_OK);
					finish();

				} catch (Exception e) {
					Log.e("error", "Error in post data", e);
				}
			}

		}
	}

	public boolean validate(String title, String org) {
		Boolean flag = false;
		if (title.isEmpty()) {

			editTitle.setError("You did not enter the Title");
			flag = true;
		}
		if (org.isEmpty()) {
			editOrganizer.setError("You did not enter the Organizer");
		}
		return flag;
	}

	@SuppressWarnings("unchecked")
	public void getCategory() {

		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/StudentEvents_Categories?APIKey=" + MainActivity.APIKEY + "&AuthToken="
				+ User.getInstance().getToken() + "&IncludeEvents=false&TitleOnly=false&Output=XML";
		DataPuller categoryListPuller = new DataPuller(new EventCategoryXmlParser());
		categoryListPuller.execute(url);
		try {
			category = (List<String>) categoryListPuller.get();
		} catch (Exception e) {
			Log.e("error", "Error in get category", e);
		}
	}

	@SuppressWarnings("unchecked")
	public void getCommittee() {

		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/StudentEvents_Committees?APIKey=" + MainActivity.APIKEY + "&AuthToken="
				+ User.getInstance().getToken() + "&IncludeEvents=false&TitleOnly=false&Output=XML";
		DataPuller committeeListPuller = new DataPuller(new EventCommitteeXmlParser());
		committeeListPuller.execute(url);
		try {
			committee = (List<String>) committeeListPuller.get();
		} catch (Exception e) {
			Log.e("error", "Error in getCommittee", e);
		}
	}
}
